﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace Pocahontas.Sitecore.Mvc
{
	public class SitecoreHtmlMetadata
	{
		private SitecoreHtmlMetadata()
		{
		}

		public SitecoreItemKey Key
		{
			get;
			set;
		}

		public string FieldName
		{
			get;
			set;
		}

		public static SitecoreHtmlMetadata FromLambdaExpression<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression, ViewDataDictionary<TModel> viewData)
		{
			SitecoreHtmlMetadata sitecoreMetadata = new SitecoreHtmlMetadata();

			ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, viewData);

			if (viewData.Model != null)
			{
				SitecoreItemKey key = SitecoreItemKeyAttribute.FindKey<TModel>(viewData.Model);

				if (key != null)
				{
					sitecoreMetadata.Key = key;
				}
				else
				{
					throw new Exception(String.Format("Item of type {0} has a null key.", typeof(TModel)));
				}
			}
			else
			{
				throw new Exception("Cannot render a field for a null model.");
			}

			string fieldName = modelMetadata.PropertyName;

			SitecoreItemFieldAttribute itemFieldAttribute = SitecoreItemFieldAttribute.GetItemFieldAttribute(viewData.Model, modelMetadata.PropertyName);

			if (itemFieldAttribute != null)
			{
				fieldName = itemFieldAttribute.Name;
			}

			sitecoreMetadata.FieldName = fieldName;

			return sitecoreMetadata;
		}
	}
}
